package com.linsir.template.office;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.linsir.common.Easy;
import com.linsir.common.render.OfficeRender;
import com.linsir.model.Menu;
import com.linsir.template.common.util.TemplateUtil;

import java.util.HashMap;

/**
 * @author yuxiaolin
 * @title: OfficeController
 * @projectName linsir-mu
 * @description: TODO
 * @date 2021/12/2 2:47 PM
 */

public class OfficeController extends Controller {
    final Controller ctrl = this;

    /** 自定义拦截器 **/
    protected OfficeIntercept intercept = null;

    public void list() {
        setAttr("para", this.getPara());
        render("/eova/template/office/list.html");
    }

    // 显示文档
    public void show() throws Exception {
        String menuCode = this.getPara(0);

        Menu menu = Menu.dao.findByCode(menuCode);
        String url = menu.getStr("url");

        intercept = TemplateUtil.initIntercept(menu.getBizIntercept());

        HashMap<String, Object> data = new HashMap<>();

        if (intercept != null) {
            try {
                intercept.init(ctrl, data);
            } catch (Exception e) {
                renderText(e.getMessage());
                return;
            }
        }

        for (String key : data.keySet()) {
            Object o = data.get(key);
            setAttr(key, o);
        }

        render(url);
    }

    // 下载文档
    public void file() throws Exception {

        String menuCode = this.getPara(0);

        Menu menu = Menu.dao.findByCode(menuCode);
        String url = menu.getStr("url");

        // PathKit.getRootClassPath()
        String path = PathKit.getWebRootPath() + url;

        intercept = TemplateUtil.initIntercept(menu.getBizIntercept());

        HashMap<String, Object> data = new HashMap<>();

        String fileType = menu.getConfig().getParams().getString("office_type");
        String fileName = menu.getStr("name") + '.' + fileType;

        if (intercept != null) {
            try {
                intercept.init(ctrl, data);
            } catch (Exception e) {
                renderJson(new Easy(e.getMessage()));
                return;
            }
        }

        render(new OfficeRender(fileType, fileName, path, data));
    }
}
